<template>
  <div class="app-container">
    <search-box :isMulti="false">
      <template slot="content">
        <div class="left-box">

          <el-form-item label="地区：">
            <el-input v-model="listQuery.areaName"
                      placeholder="请输入"
                      clearable @change="handleFilter"/>
          </el-form-item>


        </div>
        <div class="right-box">
          <el-button size="mini" type="success"
                     @click="handleCreate">新增
          </el-button>

          <el-button size="mini"
                     @click="handleFilter">查询
          </el-button>
          <el-button size="mini" type="info"
                     @click="reset">重置
          </el-button>
        </div>
      </template>
    </search-box>
    <div class="table-wrap">
      <el-table :data="list"
                style="width:100%"
                element-loading-text="Loading"
                height="600"
                width="300">
        <el-table-column
          type="index"
          width="50"
          label="序号"
        ></el-table-column>


        <el-table-column prop="areaName"
                         label="区域名称" >
        </el-table-column>
        <el-table-column prop="areaCode"
                         label="区域编号" >
        </el-table-column>

<!--        <el-table-column prop="createDate"-->
<!--                         label="创建时间">-->
<!--        </el-table-column>-->
        <el-table-column label="操作"
                         width="200">
          <template slot-scope="scope">
            <div class="scope-operate">
              <el-button type="info" size="mini" @click="handleUpdate(scope.row)">编辑
              </el-button>
              <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除
              </el-button>

            </div>
          </template>
        </el-table-column>


      </el-table>
      <pagination v-show="total>0"
                  :total="total"
                  :page.sync="listQuery.pageNumber"
                  :limit.sync="listQuery.pageSize"
                  @pagination="getList"/>
    </div>


    <!--    //dialog弹窗 在页面的最后一个</div>的上面-->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="30%"
      >
      <el-form ref="form" :model="form" :rules = 'rules' label-width="120px">
        <el-form-item label="上层区域" > <!-- 12+12=24 一个页面列的宽度之和不能超过24-->
          <el-col :span="18">
            <el-input v-model="form.parentName"></el-input>
          </el-col>
          <el-col :span="6">
            <el-button type="info" size="mini" @click="handleChoose()">选择
            </el-button>
          </el-col>
        </el-form-item>
        <el-form-item label="区域名称" prop="areaName">
          <el-input v-model="form.areaName"></el-input>
        </el-form-item>
        <el-form-item label="区域编号" prop="areaCode">
          <el-input v-model="form.areaCode"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSubmit">提 交</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">

  </span>
    </el-dialog>


    <el-dialog
      title="选择上层区域"
      :visible.sync="dialogVisibleChoose"
      width="30%"
    >

      <div>
        <el-form>
          <el-col :span="18">
          <el-form-item label="上层地区名称：">
            <el-input v-model="listQuery.areaName"
                      placeholder="请输入"
                      clearable  style="width: 260px"/>
          </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-button size="mini"
                @click="handleFilterDialogTable">查询
            </el-button>
            <el-button size="mini" type="info"
                       @click="resetDialogTable">重置
            </el-button></el-col>
        </el-form>
      </div>

      <el-table :data="listDialogTable"
                style="width:100%"
                element-loading-text="Loading"
                width="300"
                @row-dblclick="selectDialogTableInfo"
      >
        <el-table-column
          type="index"
          label="序号"
        ></el-table-column>
        <el-table-column prop="areaCode"
                         label="区域编号" >
        </el-table-column>
        <el-table-column prop="areaName"
                         label="区域名称" >
        </el-table-column>

      </el-table>
      <pagination v-show="totalDialogTable>0"
                  :total="totalDialogTable"
                  :page.sync="listQuery.pageNumber"
                  :limit.sync="listQuery.pageSize"
                  @pagination="getListDialogTable"/>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisibleChoose = false">取 消</el-button>

    </span>
    </el-dialog>

  </div>
</template>

<script>
  import { mapGetters } from 'vuex'

  import waves from '@/directive/waves' // waves directive
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination
  // 当然你也可以为了方便使用，将它注册到全局
  import bus from '@/utils/eventBus'
  import searchBox from '@/components/searchBox.vue'
  import * as areaInfo from '@/api/area/areaInfo'

  export default {
    name: 'AdminUser',
    components: { Pagination, searchBox },
    directives: { waves },
    filters: {},
    data() {
      return {
        list: null,
        listNoPage: null,
        listDialogTable: null,
        areaList: null,
        total: 0,
        totalDialogTable: 0,
        listQuery: { // 查询列表时的参数对象
          pageNumber: 1,
          pageSize: 10,
          appName: process.env.VUE_APP_APP_NAME,
          tenantIdList: []
        },
        dialogVisible: false,
        dialogVisibleChoose: false,
        dialogTitle:'',
        form:{

          isOpen:1,
          parentCode:'',
          parentName:'',
        },

        formDialog:{

        }
        ,



        rules: {
          parentCode: [{ required: true, message: '上级区域必选', trigger: 'blur' }],
          areaName: [{ required: true, message: '区域名称必填', trigger: 'blur' }],
          areaCode: [{ required: true, message: '区域编号必填', trigger: 'blur' }],
        }
      }
    },
    computed: {
      ...mapGetters([
        'selectedTenantId',
        'tenantList'
      ])
    },
    created() {

      // this.$nextTick(() => {
      //   this.$refs['form'].clearValidate()
      // })
      this.getList()

      // 监听 租户改变的事件,选择不同租户后,立马刷新数据
      bus.$on('selectedTenantIdChanged', () => {
        console.log('selectedTenantIdChanged事件触发...')
        this.getList()
      })
    },
    mounted() {
      // 测试用
      // var that = this
      // setTimeout(function() {
      //   that.dialogFormVisible = true
      // }, 5000)
    },
    beforeDestroy() { // 当路由切换到其他页面时触发
      bus.$off('selectedTenantIdChanged')
    },
    methods: { //所有的方法写在当前钩子函数下

      async getList() { // 获取列表数据
        this.listQuery.tenantIdList = []
        if (this.selectedTenantId == undefined) {
          this.tenantList.forEach((tenant, index) => {
            this.listQuery.tenantIdList.push(tenant.id)
          })
        } else {
          this.listQuery.tenantIdList.push(this.selectedTenantId)
        }
        const { content } = await areaInfo.getAreaInfoList(this.listQuery)
        this.list = content.list;
        this.total = content.totalCounts
      },

      async getListDialogTable() { // 获取列表数据
        this.listQuery.tenantIdList = []
        if (this.selectedTenantId == undefined) {
          this.tenantList.forEach((tenant, index) => {
            this.listQuery.tenantIdList.push(tenant.id)
          })
        } else {
          this.listQuery.tenantIdList.push(this.selectedTenantId)
        }
        const { content } = await areaInfo.getAreaInfoList(this.listQuery)
        this.listDialogTable = content.list;
        this.totalDialogTable = content.totalCounts
        console.log(this.totalDialogTable);
      },


      async getListNoPage() { // 获取列表数据不进行分页
        this.listQuery.tenantIdList = []
        if (this.selectedTenantId == undefined) {
          this.tenantList.forEach((tenant, index) => {
            this.listQuery.tenantIdList.push(tenant.id)
          })
        } else {
          this.listQuery.tenantIdList.push(this.selectedTenantId)
        }
        const { content } = await areaInfo.getAreaInfoListNoPage(this.listQuery)
        this.listNoPage = content;
      },

      handleFilter() {
        this.listQuery.pageNumber = 1
        this.getList()
      },

      handleFilterDialogTable() {
        this.listQuery.pageNumber = 1
        this.getListDialogTable()
      },

      //新增数据
      handleCreate() {
        this.dialogVisible = true
        this.dialogTitle='新增'
        this.form = {};
      },
      //编辑数据
      handleUpdate(row) {

        this.dialogVisible = true
        this.dialogTitle='编辑';
        this.form = row;

      },

      handleChoose(){
        this.dialogVisibleChoose = true;
        this.getListDialogTable();
      },
      //删除数据
      handleDelete(row) {

        this.$confirm('是否删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          areaInfo.deleteAreaInfo(row).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }).catch(() => {
        })
      },


      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },

      //页面表单提交
      onSubmit(){

        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.form.tenantId = this.$store.getters.selectedTenantId

            if (this.dialogTitle == '新增') {
              console.log('提交之前的数据',this.form);
              areaInfo.createAreaInfo(this.form).then((res) => {
                console.log(res)
                if (res.status == 200) {
                  this.$notify({
                    title: '成功',
                    message: '添加成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.dialogVisible = false
                  this.listQuery.areaName=null
                  this.getList()

                }
              })

            } else if (this.dialogTitle == '编辑') {

              areaInfo.updateAreaInfo(this.form).then((res) => {
                console.log(res)
                if (res.status == 200) {
                  this.$notify({
                    title: '成功',
                    message: '编辑成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.listQuery.areaName=null
                  this.dialogVisible = false
                  this.getList()

                }
              })


            }

          } else {
            console.log('error submit!!')
            return false
          }
        })


      },
      cancel(){
        this.dialogVisible = false;
        this.form = {};
      },
      reset() {
        this.listQuery = {}
        this.getList()
      } ,
      resetDialogTable() {
        this.listQuery = {}
        this.getListDialogTable()
      },
      selectDialogTableInfo(row, column){
        console.log('双击之后的数据',row);
        this.$set(this.form,'parentCode',row.areaCode)
        this.$set(this.form,'parentName',row.areaName)
        console.log('赋值之后的数据',this.form);
        this.dialogVisibleChoose = false
      },
    }
  }
</script>

<style scoped>
  .app-select {
    margin-bottom: 20px;
  }
</style>
